#!/usr/bin/bash
#
# Start VNC on the mate desktop via user 'huanian'.
# Note that it fails to start GUI via user 'hnli.
#
# By Huanian Li
# On 2024/11/19
#
# HOWTO:
# 1. Create script '~/.vnc/xstartup' and run 'chmod +x xstartup'
#    bash$ cat -n ~/.vnc/xstartup
#        1 #!/bin/bash
#        2
#        3 unset SESSION_MANAGER
#        4 unset DBUS_SESSION_BUS_ADDRESS
#        5
#        6 export GTK_IM_MODULE=ibus
#        7 export XMODIFIERS=@im=ibus
#        8 export QT_IM_MODULE=ibus
#        9
#       10 /usr/bin/mate-session
#       11 x-window-manager
#
# 2. Copy this script to ~/.vnc and save it as 'start.sh'
#
# 3. bash ~/.vnc/start.sh
#

function _initPS4
{
    export PS4='[${FUNCNAME}@${BASH_SOURCE}:${LINENO}|${SECONDS}]+ '
}

function DEBUG
{
    typeset -l s=$DEBUG
    [[ $s == "yes" || $s == "true" ]] && _initPS4 && set -x
}

function runcmd
{
    echo "$(id -un)@$(hostname)\$ $*"
    eval "$*"
    typeset rc=$?
    echo "$(id -un)@$(hostname)\$"
    return $rc
}

function check
{
    typeset pid1=$(vncserver -list | egrep '^:1' | awk '{print $NF}')
    if [[ -n "$pid1" && "$pid1" != "(stale)" ]]; then
        echo "VNC server is running, pid=$pid1, please stop it via:"
        echo ">>> vncserver -kill :1"
        return 1
    fi
    typeset pid2=$(cat ~/.vnc/*:1.pid 2> /dev/null)
    if [[ -n "$pid2" && "$pid1" != "$pid2" ]]; then
        echo "pid $pid2 is stale, please remove it via:"
        echo ">>> rm -f $(echo ~/.vnc/*:1.pid)"
        return 1
    fi
    return 0
}

function setup
{
    check || return 1

    rm -f ~/.vnc/*.log
    return 0
}

DEBUG

gm=${1:-"normal"} # XXX: Use geometry 1920x1200 by default

setup || exit 1

ret=0
if [[ "$gm" == "full" ]]; then
    runcmd vncserver :1 -localhost no -geometry 2560x1440 -depth 32
else
    runcmd vncserver :1 -localhost no -geometry 1920x1200 -depth 32
fi
(( ret += $? ))
if (( $ret != 0 )); then
    echo "Oops, failed to start the VNC server" >&2
    echo "      please check $(echo ~/.vnc/*1.log)" >&2
    exit 1
fi

runcmd "vncserver -list | grep -E '^:|^X'"
(( ret += $? ))
runcmd "ps -ef | egrep vnc | grep -v grep"
(( ret += $? ))
exit $ret
